<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title></title>
   <link rel="stylesheet" type="text/css" href="<g:createLinkTo dir="css" file="main.css"/>">
<script src="../js/application.js"></script>
<script src="../js/jquery-2.1.0.js"></script>
</head>
</head>

<body>
<% int count = 1; %>
%{--border="1" style="border-collapse: collapse;--}%

<div id="personTable">
    <g:render template="table" model="[persons: persons]"/>
</div>

<div id="pages">
    <g:paginate total="${personCount}" max="5" next="Next" prev="Prev" action="createPerson"/>
</div>
<input type="button" class="button" value="delete" onclick="deleteData('<g:createLink action="deletePerson"/>')">
<input type="button" class="button" value="add" onclick="addRows()">
</body>
</html>


<script>
    $('td').click(clickTd);
    var lastUpdatedField;
    function addRows() {
//    $("#show").find('tbody')
//        .append($())
        $('#table tr:last').after('<tr >' +
                '<td height="25 px"></td>' +
                '<td></td>' +
                '<td></td>' +
                '<td></td>' +
                '<td></td>' +
                '<td></td>' +
                '<td></td>' +
                '</tr>')
    }
    function clickTd(event) {

        if (event.currentTarget != lastUpdatedField &&
                event.currentTarget.className != 'readOnly') {

            if (lastUpdatedField != undefined) {
                setToTextField()
            }

            var content = event.currentTarget.innerText
            event.currentTarget.innerHTML = '<input onkeypress="submit()" size="' + content
                    .length + '" type="text" value="' + content + '" >'
            lastUpdatedField = event.currentTarget
        }


    }

    function setToTextField() {
        if (lastUpdatedField.firstChild.value != undefined) {
            lastUpdatedField.innerHTML = lastUpdatedField.firstChild.value
        }
    }
    function submit(e) {
        if (!e) e = window.event;
        var keyCode = e.keyCode || e.which;
        if (keyCode == '13') {
            setToTextField();

            var parent = lastUpdatedField.parentNode
            var children = parent.children

            var person = {
                id: children[0].innerText,
                name: children[1].innerText,
                age: children[2].innerText,

                city: children[3].innerText,
                street: children[4].innerText,
                number: children[5].innerText}


            $.ajax("<g:createLink action='updatePersonAJAX'/>",{data:{person: JSON.stringify(person)},
//               данные которые должны вернуться
                complete: function (data) {
                $('#personTable').html(data.responseText)
                }})
            }

        }
</script>